package com.micro.controller;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.micro.controller.request.HotelBookingRequest;
import com.micro.dto.HotelDTO;
import com.micro.dto.HotelOrderDTO;
import com.micro.entity.HotelOrder;
import com.micro.entity.Hotel;
import com.micro.service.HotelService;

@RestController
@RequestMapping("/api/hotels") // 酒店相关的 REST 端点前缀
public class HotelController {

    private static final Logger logger = LoggerFactory.getLogger(HotelController.class);

    @Autowired
    private HotelService hotelService; // 注入 HotelService

    /**
     * 根据城市搜索酒店的端点（支持中文参数）。
     * 示例: GET /api/hotels/search?city=北京
     */
    @GetMapping("/search")
    public ResponseEntity<List<HotelDTO>> searchHotels(@RequestParam String city) {
        try {
            logger.info("搜索酒店请求，城市参数: '{}'", city);
            
            if (city == null || city.trim().isEmpty()) {
                logger.warn("城市参数为空");
                return ResponseEntity.badRequest().build();
            }
            String trimmedCity = city.trim();
            logger.info("处理后的城市参数: '{}'", trimmedCity);
            List<HotelDTO> hotels = hotelService.searchHotelsByCity(trimmedCity);
            logger.info("查询到 {} 个酒店", hotels.size());
            if (!hotels.isEmpty()) {
                return ResponseEntity.ok(hotels);
            } else {
                return ResponseEntity.notFound().build(); // 如果找不到酒店，返回404
            }
        } catch (Exception e) {
            logger.error("搜索酒店时发生异常", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 根据城市搜索酒店的端点（使用POST请求避免URL编码问题）。
     * 示例: POST /api/hotels/search-post
     */
    @PostMapping("/search-post")
    public ResponseEntity<List<HotelDTO>> searchHotelsPost(@RequestParam String city) {
        try {
            logger.info("POST搜索酒店请求，城市参数: '{}'", city);
            
            if (city == null || city.trim().isEmpty()) {
                logger.warn("城市参数为空");
                return ResponseEntity.badRequest().build();
            }
            String trimmedCity = city.trim();
            logger.info("处理后的城市参数: '{}'", trimmedCity);
            List<HotelDTO> hotels = hotelService.searchHotelsByCity(trimmedCity);
            logger.info("查询到 {} 个酒店", hotels.size());
            if (!hotels.isEmpty()) {
                return ResponseEntity.ok(hotels);
            } else {
                return ResponseEntity.notFound().build(); // 如果找不到酒店，返回404
            }
        } catch (Exception e) {
            logger.error("POST搜索酒店时发生异常", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取特定酒店详情的端点。
     * 示例: GET /api/hotels/123
     */
    @GetMapping("/{hotelName}")
    public ResponseEntity<List<HotelDTO>> getHotelDetails(
            @PathVariable String hotelName,
            @RequestParam String city // city暂时必须有
    ) {
        try {
            logger.info("获取酒店详情请求，酒店名称: '{}', 城市: '{}'", hotelName, city);
            if (hotelName == null || hotelName.trim().isEmpty() || city == null || city.trim().isEmpty()) {
                logger.warn("酒店名称或城市参数为空");
                return ResponseEntity.badRequest().build();
            }
            String trimmedHotelName = hotelName.trim();
            String trimmedCity = city.trim();
            logger.info("处理后的参数 - 酒店名称: '{}', 城市: '{}'", trimmedHotelName, trimmedCity);
            List<HotelDTO> hotels = hotelService.searchHotelByNameAndCity(trimmedHotelName, trimmedCity);
            logger.info("查询到 {} 个酒店", hotels.size());
            if (!hotels.isEmpty()) {
                return ResponseEntity.ok(hotels);
            } else {
                logger.info("未找到匹配的酒店");
                return ResponseEntity.notFound().build(); // 如果找不到酒店，返回404
            }
        } catch (Exception e) {
            logger.error("获取酒店详情时发生异常", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 根据酒店ID获取酒店信息的端点。
     * 示例: GET /api/hotels/id/123
     */
    @GetMapping("/id/{hotelId}")
    public ResponseEntity<HotelDTO> getHotelById(@PathVariable Long hotelId) {
        try {
            logger.info("根据酒店ID获取酒店信息，酒店ID: {}", hotelId);
            if (hotelId == null) {
                logger.warn("酒店ID参数为空");
                return ResponseEntity.badRequest().build();
            }
            
            Hotel hotel = hotelService.getHotelById(hotelId);
            if (hotel != null) {
                HotelDTO hotelDTO = new HotelDTO(hotel);
                logger.info("找到酒店: {}", hotelDTO.getHotelName());
                return ResponseEntity.ok(hotelDTO);
            } else {
                logger.info("未找到酒店，ID: {}", hotelId);
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("根据酒店ID获取酒店信息时发生异常", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 预订酒店房间的端点。
     * 示例: POST /api/hotels/book
     * 请求体: HotelBookingRequest JSON
     */
    @PostMapping("/book")
    public ResponseEntity<HotelOrder> bookHotel(@RequestBody HotelBookingRequest request) {
        try {
            HotelOrder bookedOrder = hotelService.bookHotel(request);
            return ResponseEntity.ok(bookedOrder); // 返回创建的订单信息
        } catch (IllegalArgumentException e) {
            // 参数验证失败，返回400
            return ResponseEntity.badRequest().build();
        } catch (RuntimeException e) {
            // 其他业务异常，返回500
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 取消酒店预订的端点。
     * 示例: POST /api/hotels/cancel
     * 请求体: JSON 类似 { "orderId": 123, "userId": 456 }
     */
    @PostMapping("/cancel")
    public ResponseEntity<String> cancelBooking(@RequestParam Long orderId) {
        try {
            boolean success = hotelService.cancelBooking(orderId);
            if (success) {
                return ResponseEntity.ok("预订取消成功。");
            } else {
                // 如果 cancelBooking 返回 false，可能会进入此情况，尽管当前实现会抛出异常
                return ResponseEntity.badRequest().body("预订取消失败。");
            }
        } catch (RuntimeException e) {
            // 捕获业务异常并返回错误信息
            return ResponseEntity.badRequest().body("取消失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户酒店预订历史记录的端点。
     * 示例: GET /api/hotels/history?userId=456
     */
    @GetMapping("/history")
    public ResponseEntity<List<HotelOrderDTO>> getUserBookingHistory(@RequestParam Long userId) {
        List<HotelOrderDTO> history = hotelService.getUserBookingHistory(userId);
        if (history.isEmpty()) {
            return ResponseEntity.notFound().build(); // 如果没有预订记录，返回404
        }
        return ResponseEntity.ok(history); // 返回订单历史列表
    }
}